#!/usr/bin/python
# -*- coding:utf-8 -*-
# @Time  : 6/4/20
# @Author: yanlh
# @usage : 容器重启策略on-failure设置为5
import docker_utils


def get_plugin_info():
    plugin_info = {
        "name": "Docker_daemon_010 NetworkSettings.RestartPolicy",
        "plugin_id": "docker_daemon_0010",
        "plugin_type": "Docker_Daemon_Config_Safe",
        "info": "Ensure that the 'on-failure' container restart policy is set to '5'",
        "level": "B",
        "module": "Safety scan",
        "author": "yanlh",
        "keyword": "Safety scan",
        "configable": "false",
    }
    return plugin_info


logger = None
cur_user = None
cur_module = None
cur_task = None


def set_plugin_logger(setter, user, module, task, *args, **kwargs):
    global logger, cur_user, cur_module, cur_task
    logger = setter
    cur_user = user
    cur_module = module
    cur_task = task


def record_logger(record_list, module):
    des_list = []
    for item in record_list:
        des_list.append(item['info'])
        if item['type'] == 'info':
            logger.debug_info(cur_user, cur_module, cur_task + module, '', item['info'])
        if item['type'] == 'error':
            logger.debug_error(cur_user, cur_module, cur_task + module, '', item['info'])
        if item['type'] == 'warning':
            logger.debug_warning(cur_user, cur_module, cur_task + module, '', item['info'])
    return des_list


def parse_config(item):
    value_list = list(item.split(':'))
    if len(value_list) < 3:
        info = {'info': 'Information count is error', 'type': 'error'}
        return info, 1
    error_count = 0
    container = value_list[0].strip() if value_list[0] else None
    name = value_list[1].strip() if value_list[1] else None
    if name == 'always':
        des = 'Not Safe. Container {} config restart policies always'.format(container)
        error_count += 1
        info = {'info': des, 'type': 'warning'}
    elif name == 'on-failure':
        failure = value_list[2].strip() if value_list[2] else None
        if int(failure) > 5:
            des = 'Not Safe. Container {} config restart count greater than 5'.format(container)
            error_count += 1
            info = {'info': des, 'type': 'warning'}
        else:
            des = 'Safe. Container {} config restart count less than or equal 5'.format(container)
            info = {'info': des, 'type': 'info'}
    else:
        des = 'Safe. Container {} config restart policies are not bing used'.format(container)
        info = {'info': des, 'type': 'info'}
    return info, error_count


# 扫描函数
def scan(func_args, flag=0):
    logger.debug_info(cur_user, cur_module, cur_task + '_Scan', '', "Scan Start.")
    record_scan, error_count = docker_utils.scan_daemon_process_config(parse_config, func_args)
    scan_list = record_logger(record_scan, '_Scan')
    if flag:
        info = ['Please check and config the unsafe item manually.', 'Reinforce Complete.']
        logger.debug_info(cur_user, cur_module, cur_task + '_Reinforce', '', "Reinforce Complete.")
        scan_list.extend(info)
        return scan_list, error_count
    return scan_list, error_count


# 回滚函数
def rollback(func_args):
    des_list = ["This function don't need to rollback.", 'Rollback Complete.']
    logger.debug_info(cur_user, cur_module, cur_task + '_Rollback', '', "Rollback Complete.")
    return des_list, 0


def check(ip, *args, **kwargs):
    sys_user = kwargs.get("system_user")
    sys_pwd = kwargs.get("system_pwd")
    comm = kwargs.get("command")
    try:
        logger.debug_info(cur_user, cur_module, cur_task + '_Check', '', "docker_daemon_0010 Start.")
        func_args = {'ip': ip, 'username': sys_user, 'passwd': sys_pwd, 'comm': comm,
                     'variable': '{{.Id}}:{{.HostConfig.RestartPolicy.Name}}:{{.HostConfig.RestartPolicy.MaximumRetryCount}}'}
        result = docker_utils.check_func(scan, rollback, func_args)
        logger.debug_info(cur_user, cur_module, cur_task + '_Check', '', "docker_daemon_0010 Complete.")
        return result
    except Exception as er:
        code = 1
        des = ["ERROR:", str(er)]
        logger.debug_error(cur_user, cur_module, cur_task + '_Check', '', des)
        return {"code": code, "count": 0, "des": des}


if __name__ == '__main__':
    """
    本地测试
    """
    check(ip=None, command=1)
